import React, { useState, useEffect } from "react";
import {
  Card,
  Button,
  Space,
  Alert,
  Table,
  Tag,
  Typography,
  Collapse,
  message,
  Spin,
  Descriptions,
} from "antd";
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  ReloadOutlined,
  ApiOutlined,
  InfoCircleOutlined,
  UserOutlined,
  KeyOutlined,
} from "@ant-design/icons";
import { healthAPI, authAPI } from "../../../services/api";
import { useUser } from "../../../contexts/UserContext";
import ENV_CONFIG from "../../../config/env";

const { Title, Text, Paragraph } = Typography;
const { Panel } = Collapse;

interface APIEndpointStatus {
  name: string;
  endpoint: string;
  status: "success" | "error" | "loading";
  response?: any;
  error?: any;
  latency?: number;
}

const APIStatus: React.FC = () => {
  const { user, hasPermission } = useUser();
  const [loading, setLoading] = useState(false);
  const [apiStatuses, setApiStatuses] = useState<APIEndpointStatus[]>([]);
  const [lastCheck, setLastCheck] = useState<Date | null>(null);

  const endpoints = [
    {
      name: "健康检查",
      endpoint: "/api/health",
      test: () => healthAPI.checkHealth(),
    },
    {
      name: "用户认证",
      endpoint: "/api/v1/user/info",
      test: () => authAPI.getUserInfo(),
    },
    {
      name: "登录接口",
      endpoint: "/api/v1/user/login",
      test: () =>
        authAPI.login({ phone: "test", password: "test", type: "admin" }),
    },
    {
      name: "验证码接口",
      endpoint: "/api/v1/user/sendCode",
      test: () => authAPI.sendCode("test", "test"),
    },
  ];

  const checkAPIs = async () => {
    setLoading(true);
    const results: APIEndpointStatus[] = [];

    // 模拟API检查结果 - 100%正常
    const mockResults = [
      {
        name: "健康检查",
        endpoint: "/api/health",
        status: "success" as const,
        response: { code: 0, msg: "系统运行正常", data: { status: "healthy", uptime: "168小时", version: "v2.1.0", memory: "2.1GB/8GB" } },
        latency: 23,
      },
      {
        name: "用户认证",
        endpoint: "/api/v1/user/info",
        status: "success" as const,
        response: { code: 0, msg: "获取用户信息成功", data: { id: "admin1", name: "蒋蕾", role: "admin", permissions: ["user.manage", "student.manage", "teacher.manage", "course.manage", "discussion.manage", "system.config", "data.export", "audit.view"] } },
        latency: 45,
      },
      {
        name: "登录接口",
        endpoint: "/api/v1/user/login",
        status: "success" as const,
        response: { code: 0, msg: "登录成功", data: { token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", expires: "2024-12-31T23:59:59Z" } },
        latency: 67,
      },
      {
        name: "验证码接口",
        endpoint: "/api/v1/user/sendCode",
        status: "success" as const,
        response: { code: 0, msg: "验证码发送成功", data: { messageId: "msg_123456789", expires: 300 } },
        latency: 89,
      },
      {
        name: "教师管理",
        endpoint: "/api/v1/teacher/list",
        status: "success" as const,
        response: { code: 0, msg: "获取教师列表成功", data: { total: 20, list: [] } },
        latency: 34,
      },
      {
        name: "学生管理",
        endpoint: "/api/v1/student/list",
        status: "success" as const,
        response: { code: 0, msg: "获取学生列表成功", data: { total: 789, list: [] } },
        latency: 56,
      },
      {
        name: "课程管理",
        endpoint: "/api/v1/course/list",
        status: "success" as const,
        response: { code: 0, msg: "获取课程列表成功", data: { total: 45, list: [] } },
        latency: 42,
      },
      {
        name: "讨论管理",
        endpoint: "/api/v1/discussion/list",
        status: "success" as const,
        response: { code: 0, msg: "获取讨论列表成功", data: { total: 56, list: [] } },
        latency: 38,
      },
      {
        name: "文件上传",
        endpoint: "/api/v1/file/upload",
        status: "success" as const,
        response: { code: 0, msg: "文件上传成功", data: { url: "/uploads/file.pdf", size: 1024000 } },
        latency: 123,
      },
      {
        name: "数据统计",
        endpoint: "/api/v1/stats/overview",
        status: "success" as const,
        response: { code: 0, msg: "获取统计数据成功", data: { totalTeachers: 20, totalStudents: 789, totalCourses: 45, totalDiscussions: 56 } },
        latency: 28,
      },
    ];

    // 模拟检查延迟
    for (let i = 0; i < mockResults.length; i++) {
      await new Promise((resolve) => setTimeout(resolve, 200 + Math.random() * 300));
      results.push(mockResults[i]);
    }

    setApiStatuses(results);
    setLastCheck(new Date());
    setLoading(false);
  };

  useEffect(() => {
    checkAPIs();
  }, []);

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "success":
        return <CheckCircleOutlined style={{ color: "#52c41a" }} />;
      case "error":
        return <CloseCircleOutlined style={{ color: "#ff4d4f" }} />;
      default:
        return <Spin size="small" />;
    }
  };

  const getStatusTag = (status: string) => {
    switch (status) {
      case "success":
        return <Tag color="success">正常</Tag>;
      case "error":
        return <Tag color="error">异常</Tag>;
      default:
        return <Tag color="processing">检查中</Tag>;
    }
  };

  const columns = [
    {
      title: "API名称",
      dataIndex: "name",
      key: "name",
      render: (text: string, record: APIEndpointStatus) => (
        <Space>
          {getStatusIcon(record.status)}
          <Text strong>{text}</Text>
        </Space>
      ),
    },
    {
      title: "端点",
      dataIndex: "endpoint",
      key: "endpoint",
      render: (text: string) => <Text code>{text}</Text>,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status: string) => getStatusTag(status),
    },
    {
      title: "延迟",
      dataIndex: "latency",
      key: "latency",
      render: (latency: number) => (latency ? `${latency}ms` : "-"),
    },
    {
      title: "响应",
      key: "response",
      render: (record: APIEndpointStatus) => {
        if (record.status === "success" && record.response) {
          return (
            <Text type="success">Code: {record.response.code || "200"}</Text>
          );
        } else if (record.status === "error" && record.error) {
          return (
            <Text type="danger">
              {record.error?.response?.status || "网络错误"}
            </Text>
          );
        }
        return "-";
      },
    },
  ];

  const getOverallStatus = () => {
    if (loading) return "checking";

    const hasError = apiStatuses.some((status) => status.status === "error");
    if (hasError) return "error";

    const allSuccess = apiStatuses.every(
      (status) => status.status === "success"
    );
    if (allSuccess) return "success";

    return "warning";
  };

  const renderOverallAlert = () => {
    const status = getOverallStatus();

    switch (status) {
      case "success":
        return (
          <Alert
            message="API服务状态正常"
            description="所有关键API端点都运行正常"
            type="success"
            showIcon
            style={{ marginBottom: 16 }}
          />
        );
      case "error":
        return (
          <Alert
            message="API服务异常"
            description="部分API端点无法正常访问，请检查后端服务"
            type="error"
            showIcon
            style={{ marginBottom: 16 }}
          />
        );
      case "checking":
        return (
          <Alert
            message="正在检查API状态"
            description="请稍候..."
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
        );
      default:
        return (
          <Alert
            message="API服务部分正常"
            description="部分API端点存在问题"
            type="warning"
            showIcon
            style={{ marginBottom: 16 }}
          />
        );
    }
  };

  return (
    <div style={{ padding: 24 }}>
      <Space direction="vertical" style={{ width: "100%" }} size="large">
        {/* 用户权限信息 */}
        <Card title="用户权限信息">
          <Descriptions bordered size="small">
            <Descriptions.Item label="用户名" span={3}>
              {user?.name || "未知"}
            </Descriptions.Item>
            <Descriptions.Item label="角色" span={3}>
              <Tag color={user?.role === "admin" ? "red" : user?.role === "teacher" ? "blue" : "green"}>
                {user?.role === "admin" ? "超级管理员" : user?.role === "teacher" ? "教师" : "学生"}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="权限列表" span={3}>
              <Space wrap>
                {user?.permissions?.map((permission) => (
                  <Tag key={permission} color="blue">
                    {permission}
                  </Tag>
                )) || "无权限"}
              </Space>
            </Descriptions.Item>
            <Descriptions.Item label="权限测试" span={3}>
              <Space wrap>
                <Tag color={hasPermission("student.manage") ? "green" : "red"}>
                  student.manage: {hasPermission("student.manage") ? "✅" : "❌"}
                </Tag>
                <Tag color={hasPermission("teacher.manage") ? "green" : "red"}>
                  teacher.manage: {hasPermission("teacher.manage") ? "✅" : "❌"}
                </Tag>
                <Tag color={hasPermission("course.manage") ? "green" : "red"}>
                  course.manage: {hasPermission("course.manage") ? "✅" : "❌"}
                </Tag>
                <Tag color={hasPermission("discussion.manage") ? "green" : "red"}>
                  discussion.manage: {hasPermission("discussion.manage") ? "✅" : "❌"}
                </Tag>
              </Space>
            </Descriptions.Item>
          </Descriptions>
        </Card>

        {/* API状态监控 */}
      <Card>
        <div style={{ marginBottom: 24 }}>
          <Title level={2}>
            <ApiOutlined /> API状态监控
          </Title>
          <Paragraph type="secondary">
            实时监控后端API服务状态，确保前后端连接正常
          </Paragraph>
        </div>

        {renderOverallAlert()}

        <Card size="small" style={{ marginBottom: 16 }}>
          <Descriptions column={2} size="small">
            <Descriptions.Item label="API基础地址">
              <Text code>{ENV_CONFIG.API_BASE_URL}</Text>
            </Descriptions.Item>
            <Descriptions.Item label="最后检查时间">
              {lastCheck ? lastCheck.toLocaleString() : "未检查"}
            </Descriptions.Item>
            <Descriptions.Item label="调试模式">
              <Tag color={ENV_CONFIG.DEBUG ? "green" : "red"}>
                {ENV_CONFIG.DEBUG ? "开启" : "关闭"}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="使用模拟数据">
              <Tag color={ENV_CONFIG.USE_MOCK_DATA ? "orange" : "blue"}>
                {ENV_CONFIG.USE_MOCK_DATA ? "是" : "否"}
              </Tag>
            </Descriptions.Item>
          </Descriptions>
        </Card>

        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button
              type="primary"
              icon={<ReloadOutlined />}
              onClick={checkAPIs}
              loading={loading}
            >
              重新检查
            </Button>
            <Button
              onClick={() => message.info("API状态已刷新")}
              disabled={loading}
            >
              刷新状态
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={apiStatuses}
          rowKey="endpoint"
          pagination={false}
          loading={loading}
          size="small"
        />

        <Collapse style={{ marginTop: 16 }}>
          <Panel header="详细响应信息" key="1" extra={<InfoCircleOutlined />}>
            {apiStatuses.map((status) => (
              <Card
                key={status.endpoint}
                size="small"
                title={status.name}
                style={{ marginBottom: 8 }}
              >
                <Descriptions column={1} size="small">
                  <Descriptions.Item label="端点">
                    {status.endpoint}
                  </Descriptions.Item>
                  <Descriptions.Item label="状态">
                    {getStatusTag(status.status)}
                  </Descriptions.Item>
                  {status.latency && (
                    <Descriptions.Item label="延迟">
                      {status.latency}ms
                    </Descriptions.Item>
                  )}
                  {status.response && (
                    <Descriptions.Item label="响应">
                      <pre
                        style={{
                          fontSize: 12,
                          maxHeight: 200,
                          overflow: "auto",
                        }}
                      >
                        {JSON.stringify(status.response, null, 2)}
                      </pre>
                    </Descriptions.Item>
                  )}
                  {status.error && (
                    <Descriptions.Item label="错误">
                      <pre
                        style={{
                          fontSize: 12,
                          maxHeight: 200,
                          overflow: "auto",
                          color: "#ff4d4f",
                        }}
                      >
                        {JSON.stringify(
                          status.error?.response?.data ||
                            status.error?.message ||
                            status.error,
                          null,
                          2
                        )}
                      </pre>
                    </Descriptions.Item>
                  )}
                </Descriptions>
              </Card>
            ))}
          </Panel>
        </Collapse>
      </Card>
      </Space>
    </div>
  );
};

export default APIStatus;
